package com.geeklan.smart.utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;

import androidx.core.content.FileProvider;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class CameraUtils {
    public static final int REQUEST_CODE_CAMERA = 1001;

    public static Uri openCamera(Activity context) {
        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        // 确保有相机应用可以处理该 Intent
        if (cameraIntent.resolveActivity(context.getPackageManager()) != null) {
            // 创建临时文件存储图片
            File photoFile = createImageFile(context);
            if (photoFile != null) {
                Uri photoUri = FileProvider.getUriForFile(context, context.getPackageName() + ".provider", photoFile);
                cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
                context.startActivityForResult(cameraIntent, REQUEST_CODE_CAMERA);
                return photoUri;
            }
        }
        return null;
    }

    private static File createImageFile(Context context) {
        try {
            // 使用时间戳命名文件
            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
            String fileName = "JPEG_" + timeStamp + "_";
            File storageDir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
            return File.createTempFile(fileName, ".jpg", storageDir);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
